package com.atguigu.springcloud.filter;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONConverter;
import cn.hutool.json.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class MyFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 1、获取请求对象  
        ServerHttpRequest request = exchange.getRequest();

        // 2、获取请求路径  
        String path = request.getURI().getPath();
        System.out.println("path = " + path);

        // 3、获取请求参数  
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String userName = queryParams.get("userName").get(0);
        if ("tom".equals(userName)) {
            return synchronizeRequestRefuse(exchange);
        }

        if ("jerry".equals(userName)) {
            return aSynchronizeRequestRefuse(exchange);
        }

        // 4、放行  
        return chain.filter(exchange);
    }

    /**
     * 同步请求
     *
     * @param exchange
     * @return
     */
    private Mono<Void> synchronizeRequestRefuse(ServerWebExchange exchange) {

        // 1、获取 Response 对象  
        ServerHttpResponse response = exchange.getResponse();

        // 2、设置响应状态码：表示重定向  
        response.setStatusCode(HttpStatus.SEE_OTHER);

        // 3、指定重定向的目标地址  
        String location = "http://www.baidu.com";

        // 4、执行响应消息头：指定 location
        response.getHeaders().set("location", location);

        // 5、响应设置完成：把一个设置好的 response 对象交给框架，  
        // 框架就知道要去执行重定向了  
        return response.setComplete();
    }

    /**
     * 异步请求
     *
     * @param exchange
     * @return
     */
    private Mono<Void> aSynchronizeRequestRefuse(ServerWebExchange exchange) {

        // 1、创建 Map 对象封装数据  
        Map<String, String> map = new HashMap<>();
        map.put("k1", "v1");

        // 2、把 Result 对象转换为 JSON 字符串  
        String resultJSON = new JSONConverter().convert(map, null).toJSONString(4);

        // 3、为了后面设置响应体，JSON 字符串需要获取字节数组  
        byte[] bytes = resultJSON.getBytes();

        // 4、获取响应对象  
        ServerHttpResponse response = exchange.getResponse();

        // 5、设置响应消息头  
        response.getHeaders().set("Content-type", "application/json;charset=UTF-8");

        // 6、把字节数组放入响应缓冲区  
        DataBuffer wrap = response.bufferFactory().wrap(bytes);

        // 7、封装为 Mono 对象返回  
        return response.writeWith(Mono.just(wrap));
    }
}